<template>
	<div
		class="bar-row-chart"
		ref="myRef"
	>
	</div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, watch, defineProps, nextTick, computed , defineEmits} from 'vue'
import { cloneDeep } from 'lodash'

let myChart = null
let timer = null

let stepTimer = null

const emits = defineEmits(['getIndex'])

const props = defineProps({
	seriesData: {
		type: Array,
		default: () => {
			return []
		}
	},
	category: {
		type: Array,
		default: () => {
			return []
		}
	},
	color: {
		type: Array,
		default: () => {
			return ['#3B6DE5', '#E4AE1B', '#1ACCFF', '#3BE589']
		}
	},
	unit: {
		type: [String, Number],
		default: ''
	},
	unitRight: {
		type: [String, Number],
		default: ''
	},
	showRight: {
		type: Boolean,
		default: false
	},
	height: {
		type: [Number, String],
		default: 210
	},
	width: {
		type: [Number, String],
		default: ''
	},
	gridTop: {
		type:  [Number, String],
		default: ''
	},
  // 显示数量限制 limitCount === 0 时，不做限制 显示全部
	limitCount: {
		type: [String, Number],
		default: 20
	},
	max:{
		type: [String, Number],
		default: null
	},
	min:{
		type: [String, Number],
		default: null
	},
  splitNumber: {
    type: Number,
    default: 4
  },
  xAxisRotate: {
    type: Number,
    default: 0
  },
	showLegend: {
		type: Boolean,
		default: false
	},
	labelFontSize: {
		type: Number,
		default: 12
	},
	labelPosition: {
		type: String,
		default: ''
	}
})

const seriesList = ref([])
const seriesCategory = ref([])
const myRef = ref(null)

const limit = ref(20)
const stepNum = ref(19)

const initChart = () => {
	myChart = echarts.init(myRef.value)
	myChart.setOption({
		color: props.color,
		textStyle: {
			color: '#fff',
		},
		tooltip: {
			show: false,
			trigger: 'axis',
			borderColor: '#2E5396',
			borderWidth: 1,
			backgroundColor: '#0E2D68',
			formatter : function(params) {
				let titleStr = `<div style='width: 100%; font-size: 14px; font-weight: bold; color: #E4AE1B;'>${params[0].name}</div>`
				let contentStr = ''
				params.map((item, index) => {
					contentStr += `
					<div style='width: 100%; margin-top: 6px; font-size: 14px; color: #fff'>
          			${item.marker}
					${item.seriesName}${item.seriesName ? '：' : ''}<span style='margin-left: 2px; font-size: 14px; color: #fff'>${item.value}${props.seriesData[index]?.unit}</span>
					`
				})
				return (
					titleStr + contentStr
				)
			}
		},
		legend: {
			show: props.showLegend,
			itemWidth: 8,
			itemHeight: 4,
			itemGap: 10,
			top: '10px',
			textStyle: {
			}
		},
		grid: {
			top: props.showLegend ? '40px' : '20px',
			bottom: '20px',
			left: '0',
			right: '20px',
			containLabel: true,
		},
		xAxis: {
      type: 'value',
			axisTick: {
				show: false
			},
			axisLabel: {
				fontSize: 12,
				color: '#B9B9B9',
				rotate: props.xAxisRotate,
			}
		},
		yAxis: [
			{
				type: 'category',
				data:	seriesCategory.value,
				axisLabel: {
					color: '#363B46',
					fontSize: 12
        },
				splitLine: {
					show: false,
					lineStyle: {
						type: 'dashed',
					}
				},
				nameTextStyle: {
					color: '#B9B9B9',
					fontSize: 12,
					padding: [0, 0, 0, -25],
				}
			}
		],
		series: seriesList.value?.map(item => {
			return {
				...item,
				label: {
					formatter: params => {
						return `${params.value}${props.unit}`
					},
					show: true,
					offset: props.labelPosition === 'top' ? [0, -10] : [0, 1],
					position: 'insideLeft',
					fontSize: props.labelFontSize,
				}
			}
		})
	})

	if (props.category.length > limit.value && props.limitCount) {
		startStep()
	} else {
		startInterval()
	}

	myChart.getZr().on('mouseover', ({ offsetX, offsetY }) => {
    clearInterval(timer)
    clearInterval(stepTimer)
	})

	myChart.on('click', e => {
		emits('getIndex', e.dataIndex)
	})

  myChart.getZr().on('click', (e) => {
		// console.log(e)
  })
}

const startStep = () => {
	stepTimer && clearInterval(stepTimer)
	stepTimer = setInterval(() => {
		stepNum.value++
		if (stepNum.value > props.category?.length - 1) {
			stepNum.value = 0
		}

		seriesCategory.value.shift()
		seriesCategory.value.push(props.category[stepNum.value])

		seriesList.value.map((item, index) => {
			item.data.shift()
			item.data.push(props.seriesData[index].data[stepNum.value])
		})

		myChart.setOption({
			xAxis: {
				data: seriesCategory.value
			},
			series: seriesList.value
		})
	}, 3000)
}

const startInterval = () => {
	let pos = 0
	timer && clearInterval(timer)
	myChart && myChart.dispatchAction({
		type: 'hideTip'
	})
	myChart && myChart.dispatchAction({
		type: 'downplay'
	})
	timer = setInterval(() => {
		let seriesIndex = 0
		if (pos > 0) {
			myChart.dispatchAction({
				type: 'downplay',
				seriesIndex: seriesIndex,
				dataIndex: pos - 1
			})
		} else {
			myChart.dispatchAction({
				type: 'downplay',
				seriesIndex: seriesIndex,
				dataIndex: seriesCategory.value - 1
			})
		}

		myChart.dispatchAction({
			type: 'highlight',
			seriesIndex: seriesIndex,
			dataIndex: pos
		})
		// tooltip 跟随显示
		myChart.dispatchAction({
			type: 'showTip',
			seriesIndex: seriesIndex,
			dataIndex: pos
		})
		pos++
		if (pos > seriesCategory.value.length - 1) {
			pos = 0
		}
	}, 3000)
}

watch(() => [props.category, props.seriesData, props.limitCount], () => {
  limit.value = props.limitCount
  stepNum.value = props.limitCount - 1

	if (!props.category?.length) return
	props.seriesData.map(item => {
		if (item.type === 'bar' && !item.barWidth) item.barWidth = 8
	})
	seriesList.value = cloneDeep(props.seriesData)
	seriesCategory.value = cloneDeep(props.category)
	if (props.category.length > limit.value && props.limitCount) {
		seriesCategory.value = seriesCategory.value.splice(0, limit.value)
		seriesList.value.map(item => {
			item.data = item.data.splice(0, limit.value)
		})
	}

	nextTick(() => {
		if (myChart) myChart.dispose()
		initChart()
	})
}, { deep: true, immediate: true })
</script>

<style scoped lang="less">
.bar-row-chart {
	width: 100%;
}
</style>

